import os
import random
import time

from django.conf import settings
from qiniu import Auth, put_file, BucketManager, etag


def handle_get_file(image_id: int):
    """
    获取图片url
    :param image_id: 图片的id
    :return: 图片在存储器上的地址
    """

    # 查询对应id的row 查到继续
    #

    pass


def handle_uploaded_file(file: bytes):
    """
    上传至七牛云
    处理文件上传
    :param file: 二进制文件数据 类型为bytes
    :return: 成功返回访问url 失败返回错误
    """
    if not isinstance(file, bytes):
        raise TypeError("需要bytes类型")

    key = time.time().__str__().replace('.', '_') + "_" \
          + random.random().__str__().replace('.', "_")

    # 要上传的文件的完整路径
    file_compelte_path = settings.TEMP_FILE_SAVE_DIR.joinpath(key)

    with open(file_compelte_path, 'wb+') as f:
        f.write(file)

    # 需要填写你的 Access Key 和 Secret Key
    access_key = settings.QINIU_ACCESS_KEY
    secret_key = settings.QINIU_SECRET_KEY

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 要上传的空间
    bucket_name = settings.QINIU_BUCKET_NAME

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket=bucket_name, expires=3600)

    # 要上传文件的本地路径
    # localfile = file_compelte_path

    ret, info = put_file(token, key, file_compelte_path)

    # 上传成功检测
    if ret['key'] != key or ret['hash'] != etag(file_compelte_path):
        # 删除文件
        os.remove(file_compelte_path)
        raise Exception('上传失败')
    # 删除文件
    os.remove(file_compelte_path)
    return (settings.QINIU_URL, ret['key'])


def handle_update_file(key: str):
    # 找到key对应的对象
    pass


def handle_delete_file(key: str):
    """
    删除文件
    :param key: 要删除的文件名
    :return: None
    """

    if not isinstance(key, str):
        raise TypeError("需要str类型")

    # 需要填写你的 Access Key 和 Secret Key
    access_key = settings.QINIU_ACCESS_KEY
    secret_key = settings.QINIU_SECRET_KEY

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 要操作的数据桶
    bucket = BucketManager(q)

    bucket_name = settings.QINIU_BUCKET_NAME
    key = key

    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, key)

    if ret != {}:
        raise Exception("删除文件出错")
    return None


if __name__ == '__main__':
    # from utils.loadfile import handle_uploaded_file
    # with open(
    #         '/Users/mac/PycharmProjects/drf_admin/src/user_app/views/WechatIMG95.jpeg',
    #         'rb') as file:
    #     handle_uploaded_file(file)
    pass
